﻿
package com.ostrich.manpower.service.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.base.service.BaseService;
import com.ostrich.manpower.bean.TostHrAccfundinfo;
import com.ostrich.manpower.bean.TostHrBaseinfo;
import com.ostrich.manpower.bean.TostHrBirgiftinfo;
import com.ostrich.manpower.bean.TostHrCheckinlog;
import com.ostrich.manpower.bean.TostHrDeductinfo;
import com.ostrich.manpower.bean.TostHrFactpayinfo;
import com.ostrich.manpower.bean.TostHrHolgiftinfo;
import com.ostrich.manpower.bean.TostHrMealaddinfo;
import com.ostrich.manpower.bean.TostHrSalaryinfo;
import com.ostrich.manpower.bean.TostHrSocialsecurity;
import com.ostrich.manpower.bean.TostHrSubsalaryinfo;
import com.ostrich.manpower.bean.TostHrZhongheinfo;
import com.ostrich.manpower.common.FormulaUtil;
import com.ostrich.manpower.service.TostHrDeductinfoDao;
/**
 * @author wangyinan
 * @brief    模块功能简单描述
 * @details  模块功能详细描述
 */
@Service("tostHrDeductinfoService")
public class TostHrDeductinfoService<T> extends BaseService<T> {
	private final static Logger log= Logger.getLogger(TostHrDeductinfoService.class);

	@Autowired
    private TostHrDeductinfoDao<T> dao;
	@Autowired(required=false)
	private TostHrSalaryinfoService<TostHrSalaryinfo> tosthrsalaryinfoservice;
	
	@Autowired(required=false)
	private TostHrMealaddinfoService<TostHrMealaddinfo> tosthrmealaddinfoservice;
	
	@Autowired(required=false)
	private TostHrAccfundinfoService<TostHrAccfundinfo> tosthraccfundinfoservice;
	
	@Autowired(required=false)
	private TostHrCheckinlogService<TostHrCheckinlog> tosthrcheckinlogservice;
	
	@Autowired(required=false)
	private TostHrSocialsecurityService<TostHrSocialsecurity> tosthrsocialsecurityservice;
	
	@Autowired(required=false)
	private TostHrSubsalaryinfoService<TostHrSubsalaryinfo> tosthrsubsalaryinfoservice;

	@Autowired(required=false)
	private TostHrFactpayinfoService<TostHrFactpayinfo> tosthrfactpayinfoservice;
	
	@Autowired(required=false)
	private TostHrBirgiftinfoService<TostHrBirgiftinfo> tosthrbirgiftinfoservice;
	
	@Autowired(required=false)
	private TostHrHolgiftinfoService<TostHrHolgiftinfo> tosthrholgiftinfoservice;
	
	@Autowired(required=false)
	private TostHrZhongheinfoService<TostHrZhongheinfo> tosthrzhongheinfoservice;
	
	
	public TostHrDeductinfoDao<T> getDao() {
		return dao;
	}
	
	public List<T> queryByHrid(Integer hrid) {
		return getDao().queryByHrid(hrid);
	}
	public List<T> queryByHrMonthHrId(String hrMonth,int hrId){
		return dao.queryByHrMonthHrId(hrMonth, hrId);
	}
	public List<T> queryDeductById(Integer id){
		return dao.queryDeductById(id);
	}
	public void deleteByhrMonth(String hrMonth,int hrId){
		dao.deleteByhrMonth(hrMonth,hrId);
	}
	
	public TostHrDeductinfo chenklogs(String hmeMonth,TostHrBaseinfo bsinfo) throws Exception{
		TostHrDeductinfo checklog=new TostHrDeductinfo();
		//病事假/违纪扣款
		List<TostHrCheckinlog> ls= (List<TostHrCheckinlog>) tosthrcheckinlogservice.queryBychencks(bsinfo.getId(), hmeMonth);
			TostHrCheckinlog  hm = ls.get(0);
			checklog.setHdeSickviolate(hm.getHciDeductionsTotal());
		return checklog;
	}
	
	/****
	 * 添加扣除表
	 * @param hmeMonth
	 * @param bsinfo
	 * @return
	 * @throws Exception
	 */
	public TostHrDeductinfo addDeduc(String hmeMonth,TostHrBaseinfo bsinfo) throws Exception{
		TostHrDeductinfo dtsl=new TostHrDeductinfo();
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("hmeMonth",hmeMonth);
		map.put("hrId",bsinfo.getId());
		
		dtsl.setHrId(bsinfo.getId());
		dtsl.setHdeMonth(hmeMonth);
		
		//生日、节日礼金。
		Float bir,gir;
		TostHrBirgiftinfo thb = tosthrbirgiftinfoservice.queryBirgift(bsinfo.getId(),hmeMonth);
		TostHrHolgiftinfo thh = tosthrholgiftinfoservice.queryHolgift(bsinfo.getId(),hmeMonth);
		if(thb==null)
			bir = new Float(0);
		else
			bir = thb.getHbrSalary()!=null?thb.getHbrSalary():new Float(0);
		if(thh==null)
			gir = new Float(0);
		else
			gir = thh.getHhoSalary()!=null?thh.getHhoSalary():new Float(0);
		
		//查询工资综合表
		TostHrZhongheinfo thz = tosthrzhongheinfoservice.queryZhongheByhrid(bsinfo.getId(),hmeMonth);
		if(thz==null){
			thz = new TostHrZhongheinfo();
			thz.setHzhOtherdeduct(new Float(0));
		}
		//其他扣款 从工资综合表来的数据
		dtsl.setHdeOthdeduc(thz.getHzhOtherdeduct());
		//口购房车借款
		dtsl.setHdeBuckleborrow(bsinfo.getHrLoadmoney());
		//病事假扣款
		Float bin;
		TostHrCheckinlog thc = tosthrcheckinlogservice.queryBychencks(bsinfo.getId(), hmeMonth);
		if(thc==null)
			bin = new Float(0);
		else
			bin = thc.getHciDeductionsTotal()!=null?thc.getHciDeductionsTotal():new Float(0);
		dtsl.setHdeSickviolate(bin);
		
		//查询扣款表是否有已经生成的数据，如果有就不再重新生成工资信息
		List<TostHrDeductinfo> lst=(List<TostHrDeductinfo>) dao.queryByDeductid(map);
			
			//餐费扣款
				List<TostHrMealaddinfo> ls= tosthrmealaddinfoservice.queryIdHridHme(hmeMonth, bsinfo.getId());
				if(ls!=null&& ls.size()>0){
					TostHrMealaddinfo  hm = ls.get(0);
					dtsl.setHdeBillpayment(hm.getHmeMealeduction());
				}
		//住房公积金
				List<TostHrAccfundinfo> Accf= tosthraccfundinfoservice.queryAccfunds(hmeMonth, bsinfo.getId());
				if(Accf!=null&& Accf.size()>0){
					TostHrAccfundinfo  hm = Accf.get(0);
					dtsl.setHdeHousingfund(hm.getHacFactpersonpay());
				}
		//扣失业保险  扣医疗保险  扣养老保险
				List<TostHrSocialsecurity> Social= tosthrsocialsecurityservice.queryScocial(hmeMonth, bsinfo.getId());
				if(Social!=null&& Social.size()>0){
					TostHrSocialsecurity  hm = Social.get(0);
					dtsl.setHdeBuckleunwork(hm.getHsoIndpay());
					dtsl.setHdeBucklemedical(hm.getHsoMedindividual());
					dtsl.setHdeBuckleinsurance(hm.getHsoIndividpay());
				}
		//扣款小计 :失业保险+医疗保险+养老保险+餐费扣款+住房公积金+其他扣款+购房车借款+病事假扣款
				Float t1=(dtsl.getHdeBuckleunwork()==null)?new Float(0):dtsl.getHdeBuckleunwork();
				Float t2=(dtsl.getHdeBucklemedical()==null)?new Float(0):dtsl.getHdeBucklemedical();
				Float t3=(dtsl.getHdeBuckleinsurance()==null)?new Float(0):dtsl.getHdeBuckleinsurance();
				Float t4=(dtsl.getHdeBillpayment()==null)?new Float(0):dtsl.getHdeBillpayment();
				Float t5=(dtsl.getHdeHousingfund()==null)?new Float(0):dtsl.getHdeHousingfund();
				Float t6=(dtsl.getHdeOthdeduc()==null)?new Float(0):dtsl.getHdeOthdeduc();
				Float t7=(dtsl.getHdeBuckleborrow()==null)?new Float(0):dtsl.getHdeBuckleborrow();
				Float t8=(dtsl.getHdeSickviolate()==null)?new Float(0):dtsl.getHdeSickviolate();
				
			dtsl.setHdeCount(t1+t2+t3+t4+t5+t6+t7+t8);
				
		//扣款合计：病事假扣款+其他扣款（工资综合表）+扣个人养老+扣个人医疗+扣个人失业+扣个人住房公积金(个人实缴金额)
			dtsl.setHdeTotal(t8+t6+t3+t2+t1+t5);
		//计税工资	
			//获取补贴表的当月的合计费用
			List<TostHrSubsalaryinfo> hrIdbySub = (List<TostHrSubsalaryinfo>) tosthrsubsalaryinfoservice.queryByHrMonthHrid(hmeMonth, bsinfo.getId());
			Float subtotal = new Float(0);					 
			if(hrIdbySub!=null&&hrIdbySub.size()>0){
				TostHrSubsalaryinfo sb =hrIdbySub.get(0); 
				subtotal=sb.getHsuAccount();
			}
			//获取应付表的当月的合计费用
			List<TostHrFactpayinfo> hrIdbyFact=(List<TostHrFactpayinfo>) tosthrfactpayinfoservice.queryByHrMonthHrid(hmeMonth,bsinfo.getId());
			Float fctotal = new Float(0);
			if(hrIdbyFact!=null&&hrIdbyFact.size()>0){
				TostHrFactpayinfo fc = hrIdbyFact.get(0);
				fctotal=fc.getHfaCount();
			}
			//计税工资（补贴工资表合计+应付表合计-扣款合计+生日礼金+节日礼金-3500的免税工资）  
			Float texsalary =(subtotal+fctotal-dtsl.getHdeTotal()+bir+gir)-3500;
			texsalary=(texsalary>=0)?texsalary:0;
			dtsl.setHdeTaxlotwages(texsalary);
			//Long texsalary
			//个人所得税（应税所得*税率-速算扣除）= 应纳个人所得税
			BigDecimal texrate=(BigDecimal) FormulaUtil.formulaById(16,texsalary,texsalary,texsalary,texsalary,texsalary,texsalary,texsalary,texsalary).get("tex");
			Long deduct = (Long) FormulaUtil.formulaById(14,texsalary,texsalary,texsalary,texsalary,texsalary,texsalary,texsalary).get("rcout");
			Float texratef=Float.valueOf(texrate.toString());
			Float deductf=Float.valueOf(deduct.toString());
			dtsl.setHdePerpayable(texsalary*texratef-deductf);
			
			//计税工资（补贴工资表合计+应付表合计-扣款合计-3500的免税工资） 不加生日，节日礼金。 的计税。用作算福利（节日，生日礼金）的税金。
			Float texsalaryfuli =(subtotal+fctotal-dtsl.getHdeTotal())-3500;
			texsalaryfuli=(texsalaryfuli>=0)?texsalaryfuli:0;
			//Long texsalary
			//个人所得税（应税所得*税率-速算扣除）= 应纳个人所得税
			BigDecimal texratefuli=(BigDecimal) FormulaUtil.formulaById(16,texsalaryfuli,texsalaryfuli,texsalaryfuli,texsalaryfuli,texsalaryfuli,texsalaryfuli,texsalaryfuli,texsalaryfuli).get("tex");
			Long deductfuli = (Long) FormulaUtil.formulaById(14,texsalaryfuli,texsalaryfuli,texsalaryfuli,texsalaryfuli,texsalaryfuli,texsalaryfuli,texsalaryfuli).get("rcout");
			Float texrateffuli=Float.valueOf(texratefuli.toString());
			Float deductffuli=Float.valueOf(deductfuli.toString());
			//不加生日，节日礼金的 税金。
			Float fulijishui = texsalaryfuli*texrateffuli-deductffuli;
			//生日，节日礼金的税金=加生日，节日礼金的个税-不加生日，节日礼金的个税。
			dtsl.setHdeTaxwelfare(dtsl.getHdePerpayable()-fulijishui);
			
			if(lst!=null && lst.size()>0){
				dtsl.setId(lst.get(0).getId());
				dao.update((T) dtsl);
			}else
				dao.add((T) dtsl);
			
		return dtsl;
	}
	
public TostHrDeductinfo addTostHrDeductinfo(String hmeMonth,int hrId) throws Exception{

	TostHrDeductinfo thd=new TostHrDeductinfo();//扣款表对象
	    thd.setHrId(hrId);
		if(tosthrsalaryinfoservice.isSalary(hmeMonth, hrId)){
			//工资表已经生成过了，如需生成请点击重新生成。
			System.out.println("工资表已经生成过了。请点击重新生成！");
		}else if(!tosthrsalaryinfoservice.isHrMealadByMouth(hmeMonth,hrId)){
			//餐补表为空
			System.out.println("餐补表为空！");
		}else if(!tosthrsalaryinfoservice.isAccfundinfo(hrId)){
			System.out.println("公积金表为空");
		}
		else if(!tosthrsalaryinfoservice.isCheckInlog(hrId)){
			System.out.println("考勤表为空");
		}
		else if(!tosthrsalaryinfoservice.isSocialsecurity(hrId)){
			System.out.println("Socialsecurity表为空");
		}
		else {
			List<TostHrMealaddinfo> mealaddlist=tosthrmealaddinfoservice.queryIdHridHme(hmeMonth,hrId);
			for(TostHrMealaddinfo thmi:mealaddlist){
				thd.setHdeBillpayment(thmi.getHmeMealeduction());//餐补扣款
			}
			List<TostHrAccfundinfo> acclist= tosthraccfundinfoservice.queryAccfund(hrId);
			for(TostHrAccfundinfo tai: acclist){
				thd.setHdeHousingfund(tai.getHacFactamount());//住房公积金
			}
			List<TostHrCheckinlog> checklist =tosthrcheckinlogservice.queryCheckInLogByHrId(hrId);
			for(TostHrCheckinlog tci:checklist){
					thd.setHdeSickviolate(tci.getHciDeductionsTotal());//考勤扣款
			}
			List<TostHrSocialsecurity> soclist=tosthrsocialsecurityservice.queryScoci(hrId);
			for(TostHrSocialsecurity tsl:soclist){
				thd.setHdeBuckleunwork(tsl.getHsoUnemploysub());//扣失业保险
				thd.setHdeBucklemedical(tsl.getHsoPsubtotal());//医疗保险
				thd.setHdeBuckleinsurance(tsl.getHsoMedicalsub());//养老保险
			}
			
			//thd.setHdeBuckleborrow((float) 123);//?????口购房车借款
			//thd.setHdeOthdeduc((float) 12123);//?????扣其他借款
			//thd.setHdePerpayable((float) 1234);//??????扣个人所得税
			//thd.setHdeTaxvalue((float) 123);//?????合并剪税值
			//thd.setHdeTaxweal((float) 123);//??????合并记税1
			//thd.setHdeTaxwelfare((float) 123);//????合并记税2
			//thd.setHdeTaxlotwages((float) 123);//??????计税工资
			thd.setHdeCount((float) 123);//？？？？扣款小计，
			
			this.add((T) thd);
		}
		return thd;	
	}
}
